public without sharing class CustomerRightsApplicationController {

	public String msg {get;set;}
	public Boolean isErr {get;set;}
	public Boolean isSuccess {get; private set;}//是否保存成功
	public CustomerRightsApplication__c ca{get;private set;} 
	public String caId {get;  set;}

	public String otype {get;set;}
	public String atype {get;set;}
	public String userid {get;set;}
	public String pLine {get;set;}
	public String reason {get;set;}

	public String searchJson {get;set;}
	public String dataJson {get;set;}

	public String saveJson {get;set;}

	public Boolean isNew ;



	public String username {get;private set;}
	public String profilename {get; private set;}

	public String applicationTypeCombobox {private set;get;}
	public String rightTypeCombobox {private set;get;}
	public String saletypeCombobox {private set;get;}
	public String area1Combobox {private set;get;}
	public String area2Combobox {private set;get;}
	public String areaCombobox {private set;get;}
	public String recordTypeCombobox {private set;get;}
	public String productLineCombobox {private set;get;}
	public String systemCombobox {private set;get;}

	public String company {get; private set;}
	public boolean isOversea ; 
	public String shortcompany;
	public User currentUser {get;private set;}
	public Boolean isSaler {get; private set;}
	public Set<Id> userRoleSet ;

	public class ControllerException extends Exception {}

    public CustomerRightsApplicationController() {
        
    }
    public CustomerRightsApplicationController(ApexPages.StandardController stdController){}


    @RemoteAction
    public static List<Map<String,String>> findUser(String username, String company   ){

    	List<Map<String,String>> mcL  = new List<Map<String,String>>();

    	if(username == null || username.trim().length() == 0) return mcL;
    	username = '%'+username.trim()+'%'; 
    	//
    	System.debug(username);
    	System.debug(company);

    	for(User mc :[select Id,Name,FXProductLine__c,Profile.Name  from User where  Name like: username  and SubCompany__c =:company limit 10 ]){
    		Map<String,String> mMap = new Map<String,String>();
    		mMap.put('Id', mc.Id);
    		mMap.put('Name', mc.Name );
    		mMap.put('ProductLine', mc.FXProductLine__c );
    		mMap.put('ProfileName', mc.Profile.Name);
    		mcL.add(mMap);
    	}
    	return mcL;

    }
    private Set<Id> getRoleSet(){
    	if( userRoleSet == null){
    		userRoleSet = ImportObject.getSubRoleSet(new Set<Id>{currentUser.UserRoleId});
    	}
    	return userRoleSet;
    }
    private void setCompanyArea(){
    	Map<String ,String> comMap = new Map<String,String>();
    	for(String com : Label.ShortCompanyName.split(',',-1)){
    		List<String> cs = com.split('-',-1);
    		if(cs != null && cs.size() > 1)comMap.put(cs[0],cs[1]);
    	}
		shortcompany = comMap.get(ImportObject.getPicklistValues('Contract__c','Corpcode__c',false).get(company));
		Map<String,String> area  = new Map<String,String>();
		for (String s :  comMap.values()) {
			area.put(s, s);
		}
			area.put('东区', '东区');
			area.put('西区', '西区');
			area.put('南区', '南区');
			area.put('北区', '北区');
			area.put('中区', '中区');

    	areaCombobox = getOptMap(area);
    }
    public void next(){


        try {
            msg = '';
            isSuccess = false;
            otype = otype.trim() == '' ? null :  otype.trim();

            /*if((ca.CustomerRightsType__c != atype || ca.OperationType__c != otype ) && caId != null){
                System.debug('==>删除明细');
                delete [select Id from CustomerRightsDetails__c where CustomerRightsApplication__c =: caId ];
            }*/
            ca.ProductLineNew__c = pLine;

            ca.User__c = userid;
            ca.CustomerRightsType__c = atype.trim();
            ca.OperationType__c = otype ;
            if(String.isBlank(ca.CustomerRightsType__c))throw new DmlException('客户权限申请类型不能为空!');
            ca.Reason__c = reason.trim(); 
            isSuccess = true;
            System.debug('next=>'+ ca);
            
        }catch (Exception e) {
        
            msg = '设置失败:'+e.getMessage();

        }
        

    	

    }


    public void init (){
    	isNew = false;
    	ca = new CustomerRightsApplication__c();
        caId = System.currentPageReference().getParameters().get('id');
        setNil();
        currentUser = [select Id,Name ,Profile.Name ,UserRoleId, FXProductLine__c,SubCompany__c  from User where Id =:UserInfo.getUserId()];
        isSaler = currentUser.Profile.Name.contains('销售员');
    	try {
    		if(caId != null){

    			if(Id.valueOf(caId).getSObjectType() != CustomerRightsApplication__c.SObjectType )setErr('页面打开错误!');
    			
    			ca = [select Id ,Status__c  , CustomerRightsType__c , OperationType__c , User__c ,
    			User__r.Name , ProductLineNew__c ,Reason__c  ,User__r.Profile.Name  , Company__c , 
    			Owner.Profile.Name 
    			 from CustomerRightsApplication__c where Id=:caId ];
    			
    			 username = ca.User__r.Name; 
    			 profilename = ca.User__r.Profile.Name ;

    			 company = ca.Company__c; 

    			 isOversea = ca.Owner.Profile.Name.contains('海外');

    			if(ca.Status__c == '审批中' || ca.Status__c == '审批成功') setErr('客户权限申请' +ca.Status__c +', 不能修改!');

    		}else{

    			ca.Status__c = '草稿';
    		
    			ca.Company__c = currentUser.SubCompany__c ; 
    			company = currentUser.SubCompany__c ; 
    			isNew = true ; 
    			isOversea = currentUser.Profile.Name.contains('海外');

    		}
    		setCompanyArea();
    		applicationTypeCombobox = getOptMap(ImportObject.getPicklistValues('CustomerRightsApplication__c', 'CustomerRightsType__c', false));
    		rightTypeCombobox = getOptMap(ImportObject.getPicklistValues('CustomerRightsApplication__c', 'OperationType__c', false));
    		productLineCombobox = getOptMap(ImportObject.getPicklistValues('User', 'FXProductLine__c', false));
    		saletypeCombobox = getOptMap(ImportObject.getPicklistValues('Account', 'DirectSale__c', false));
    		area1Combobox = getOptMap(ImportObject.getPicklistValues('Country__c', 'Area1__c', false));
    		area2Combobox = getOptMap(ImportObject.getPicklistValues('Country__c', 'Area2__c', false));

    		systemCombobox = getOptMap(ImportObject.getPicklistValues('Account', 'System__c', false));
    		recordTypeCombobox = getRecordOpts();

    	}catch (Exception e) {
    		ApexPages.addMessage( new ApexPages.Message(ApexPages.Severity.ERROR ,e.getMessage()));

    	}
    	
    }

    public String getRecordOpts( ){

      Map<String,String> tmpMap = new Map<String,String>();

        for (RecordType r   :Database.query('select Name  from RecordType where  SObjectType=\'Account\' ' ) ){
            tmpMap.put(r.Name , r.Name );
        }
        return getOptMap(tmpMap);
    }

    private String getOptMap(Map<String,String> opts){
       Map<String ,Object> cooMap = new Map<String ,Object> ();
      cooMap.put('valueField', 'value');
      cooMap.put('textField', 'label');
      cooMap.put('panelHeight', '200');
      cooMap.put('limitToList', 'true');
      List<Map<String,String>>  dList = new List<Map<String,String>>();
      for (String k : opts.keySet()) {
        Map<String ,String> dataMap = new Map<String,String>();
        dataMap.put('label',opts.get(k) );
        dataMap.put('value',k );
        dList.add(dataMap);
      }  
      cooMap.put('data', dList);   
      
      return EncodingUtil.urlEncode(JSON.serialize(cooMap), 'UTF-8');
    }
    public void getDetails (){

    	if(caId != null){


	    	String sql = ' select Id,Account__c ,Account__r.Name,Account__r.TureProvince__r.Name ,Account__r.Province__r.Name,Account__r.Area__c, '+
	    	'  Account__r.City__r.Name ,Account__r.District__r.Name  , Account__r.DirectSale__c , Account__r.Owner.Name , Account__r.System__c ,'+
	    	' Account__r.AccountNumber ,Account__r.Country__r.Name  , Account__r.RecordType.Name ,Account__r.Country__r.Area2__c,Account__r.Country__r.Area1__c ' +
	    	'  from CustomerRightsDetails__c  where CustomerRightsApplication__c =\''+caId +'\' ' ;

	    
	    	List<AccountBean> tmp = new List<AccountBean>();
	    	for (CustomerRightsDetails__c crd : Database.query(sql)) {
	    		tmp.add(new AccountBean(crd,shortcompany));
	    	}
	    	dataJson = EncodingUtil.urlEncode(JSON.serialize(tmp), 'UTF-8');


    	}

    }
    public void setNil(){

    	searchJson = '{}';
    	dataJson = '[]';

    }

    private String transStr (Set<Id> nset){
    	if(nset == null || nset.size()== 0)return '()';
    	String s = JSON.serialize(nset);
    	s = s.replaceAll('"','\'');
		s = s.replace('[','(');
		s = s.replace(']',')');
		System.debug(s);
		return s;

    }
    ///检索客户
    public void search (){

    	Map<String ,Object > searchMap = (Map<String ,Object >) JSON.deserializeUntyped(EncodingUtil.urlDecode(searchJson, 'UTF-8'));

    	AccountBean ab = new AccountBean(searchMap);

    	String sql = ' select Id ,Name,TureProvince__r.Name ,Province__r.Name,'+
    	'  City__r.Name ,District__r.Name  , DirectSale__c , Owner.Name , System__c ,Area__c , '+
    	' AccountNumber ,Country__r.Name  , RecordType.Name,Country__r.Area1__c,Country__r.Area2__c ' +
    	'  from Account   where AccountNumber != \'JKDYKH\'  and Name !=\'迈克测试\' ';
    	if(ab.name != null && ab.name != '')sql += ' and Name like \'%'+ab.name+'%\' ';
    	if(ab.accountNumber != null && ab.accountNumber != '')sql += ' and accountNumber = \''+ab.accountNumber+'\' ';
    	if(ab.country != null && ab.country != '')sql += ' and Country__r.Name like \'%'+ab.country+'%\' ';
    	if(ab.trueProvince != null && ab.trueProvince != '')sql += ' and TureProvince__r.Name like \'%'+ab.trueProvince+'%\' ';
    	if(ab.province != null && ab.province != '')sql += ' and Province__r.Name like \'%'+ab.province+'%\' ';
    	if(ab.city != null && ab.city != '')sql += ' and City__r.Name  like \'%'+ab.city+'%\' ';
    	if(ab.district != null && ab.district != '')sql += ' and District__r.Name like \'%'+ab.district+'%\' ';
    	if(ab.saletype != null && ab.saletype != '')sql += ' and DirectSale__c = \''+ab.saletype+'\' ';
    	if(ab.ownerName != null && ab.ownerName != '')sql += ' and Owner.Name like \'%'+ab.ownerName+'%\' ';
    	if(ab.thridSystem != null && ab.thridSystem != '')sql += ' and ParentId != null  and  System__c like \'%'+ab.thridSystem+'%\' ';
    	if(ab.recordtype != null && ab.recordtype != '')sql += ' and RecordType.Name = \''+ab.recordtype+'\' ';
    	if(ab.area1 != null && ab.area1 != '')sql += ' and Country__r.Area1__c = \''+ab.area1+'\' ';
    	if(ab.area2 != null && ab.area2 != '')sql += ' and Country__r.Area2__c = \''+ab.area2+'\' ';
    	if(isOversea){
    		sql += ' and Account.RecordType.DeveloperName   in (\'DealerAbroad\', \'TerminalCustomerAbroad\', \'PublicRelationshipAbroad\' )  ';
    	}else{
    		sql += ' and Account.RecordType.DeveloperName not in (\'DealerAbroad\', \'TerminalCustomerAbroad\', \'PublicRelationshipAbroad\' ) ';
    	}
    		

    	if(ca.CustomerRightsType__c == '客户责任人转移' ){

    		sql += ' and Account.OwnerId != \''+ca.User__c+'\' ';

    		sql += ' and  ( Account.Owner.UserRoleId in ' +transStr( getRoleSet() ) ;

    		if(currentUser.Profile.Name == '销售管理部助理' ||currentUser.Profile.Name == '海外销售助理'||currentUser.Profile.Name == '子公司经理' ){
    			if(shortcompany == '迈克生物'){

					sql += '  or  Account.Area__c  in (\''+shortcompany+'\' , \'东区\', \'西区\', \'南区\', \'北区\', \'中区\' )  ';
    			}else{

    				sql += ' or Account.Area__c =\''+shortcompany+'\'  ' ;
    			}
    		}
    		sql += '  ) '; 
    		if(currentUser.Profile.Name.contains('销售员'))sql+= ' and Account.OwnerId = \''+currentUser.Id+'\' ';

    	
    	}
    	if(ca.CustomerRightsType__c == '客户团队权限共享' && ca.OperationType__c == '删除共享权限' ){
    		
    		sql  += ' and Id in (select AccountId from AccountTeamMember where UserId =\''+ca.User__c+'\' )';
    	}
    	if(ca.CustomerRightsType__c == '客户团队权限共享' && ca.OperationType__c == '新增共享权限'){

    		sql  += '  and Account.OwnerId != \''+ca.User__c+'\' ';
    	}

    	sql += ' limit 4000 ';

    	System.debug('===>'+sql);
    
    	//
    	List<AccountBean> tmp = new List<AccountBean>();
    	for (Account acc : Database.query(sql)) {
    		tmp.add(new AccountBean(acc,shortcompany));
    	}
    	dataJson = EncodingUtil.urlEncode(JSON.serialize(tmp), 'UTF-8');

    }

    private String getStringValue(Object o ){
    	if(o == null) return null ; 
    	return String.valueOf(o).trim();
    	
    }
    private void setErr(String message){
    	isErr  =true;
    	throw new ControllerException(message);
    }


    public void saveData(){
        isSuccess = false;
    	msg = '';
    	List<Object > resList  = (List<Object >) JSON.deserializeUntyped(EncodingUtil.urlDecode(saveJson, 'UTF-8'));
    	if(resList.size() == 0) {
    		msg = '没有数据!';
    		return;
    	}

  
    	List<CustomerRightsDetails__c> crdList = new List<CustomerRightsDetails__c>();
    	for (Object o  : resList) {
    		Map<String,Object> mo = (Map<String,Object> ) o ; 
    		CustomerRightsDetails__c crd = new CustomerRightsDetails__c();
    		if(mo.get('accid') == null || String.valueOf(mo.get('accid')).trim() == '' ){
    			msg = String.valueOf(mo.get('name')) +',该客户数据异常!' ; 
    			return ;
    		}
    		if(mo.get('isMatch') != null &&  Boolean.valueOf(mo.get('isMatch')) == false  )crd.Note__c =  '非子公司行政区域客户';
    		crd.Account__c =  String.valueOf(mo.get('accid')).trim();
    		crdList.add(crd);
    	}
    	SavePoint sp = Database.setSavepoint();

    	try {
    	   
    	   upsert ca; 
    	   delete [select Id from CustomerRightsDetails__c where CustomerRightsApplication__c =: ca.Id ];

    	   for (CustomerRightsDetails__c crd  : crdList) {
    	   		crd.CustomerRightsApplication__c = ca.Id ; 

    	   }
    	   if(crdList.size() > 0) insert crdList;
    	   msg = '保存成功!';
    	   isSuccess = true; 
    	   caId = ca.Id ; 
    	}catch (Exception e) {
    	    Database.rollback(sp);
    	    if(isNew) {
    	    	ca.Id = null ; 
    	    	caId = null; 
    	    }
    	    msg = '保存失败: '+ e.getMessage();

    	}
    	

    }

    public class AccountBean {
    	public String name ; 
    	public String accountNumber ; 
    	public String country ; 
    	public String trueProvince ; 
    	public String province ; 

    	public String city; 
    	public String district ;
    	public String saletype ;  

    	public String ownerName ; 
    	public String thridSystem ; 
    	public String recordtype; 
    	public String accid ; 

    	public String area1 ; 
    	public String area2 ;
    	public String area ;  
    	public Boolean isMatch ; 

    	public AccountBean(Account acc,String com ){
    		name = acc.Name;
    		accid = acc.Id; 
    		accountNumber = acc.AccountNumber ; 

    		country = acc.Country__r.Name;
    		province = acc.Province__r.Name;

    		trueProvince = acc.TureProvince__r.Name;
    		city = acc.City__r.Name; 
    		district = acc.District__r.Name;

    		saletype = acc.DirectSale__c; 
    		ownerName = acc.Owner.Name; 

    		thridSystem = acc.System__c ; 
    		recordtype = acc.RecordType.Name; 
    		area1 = acc.Country__r.Area1__c;
    		area2 = acc.Country__r.Area2__c;
    		area = acc.Area__c; 
    		isMatch =  judgeMatch(area,com );


    	}
    	public AccountBean(CustomerRightsDetails__c acc ,String com ){
    		name = acc.Account__r.Name;
    		accid = acc.Account__c; 
    		accountNumber = acc.Account__r.AccountNumber ; 

    		country = acc.Account__r.Country__r.Name;
    		province = acc.Account__r.Province__r.Name;

    		trueProvince = acc.Account__r.TureProvince__r.Name;
    		city = acc.Account__r.City__r.Name; 
    		district = acc.Account__r.District__r.Name;

    		saletype = acc.Account__r.DirectSale__c; 
    		ownerName = acc.Account__r.Owner.Name; 

    		thridSystem = acc.Account__r.System__c ; 
    		recordtype = acc.Account__r.RecordType.Name; 
    		area1 = acc.Account__r.Country__r.Area1__c;
    		area2 = acc.Account__r.Country__r.Area2__c;
    		area = acc.Account__r.Area__c; 
    		isMatch =  judgeMatch(area,com );


    	}

    	public AccountBean(Map<String,Object> o ){

    		name = getStringValue(o.get('name'));
    		accid = getStringValue(o.get('accid'));
    		accountNumber = getStringValue(o.get('accountNumber'));
    		country = getStringValue(o.get('country'));
    		province = getStringValue(o.get('province'));
    		trueProvince = getStringValue(o.get('trueProvince'));
    		city = getStringValue(o.get('city'));
    		district = getStringValue(o.get('district'));
    		saletype = getStringValue(o.get('saletype'));
    		ownerName = getStringValue(o.get('ownerName'));
    		thridSystem = getStringValue(o.get('thridSystem'));
    		recordtype = getStringValue(o.get('recordtype'));
    		area1 = getStringValue(o.get('area1'));
    		area2 = getStringValue(o.get('area2'));
    		area = getStringValue(o.get('area'));

    	}

    	private String getStringValue(Object o ){
    		if(o == null) return null ; 
    		return String.valueOf(o).trim();
    	
    	}
    	private Boolean judgeMatch(String area , String company ){

    		if( company == '迈克生物' && (area == '东区'||area == '南区'|| area == '西区'|| area == '北区'||area == '中区' ||area == '迈克生物'  )  ){

    			return true; 
    		}else if(company == area){
    			return true ; 
    		}
    		return false;
    	}


    }


}